﻿using TimerJobServer.Common.Mina;
using log4net;
using log4net.Repository.Hierarchy;
using Mina.Core.Service;
using Mina.Filter.Codec;
using Mina.Filter.Codec.Serialization;
using Mina.Filter.Codec.TextLine;
using Mina.Filter.Logging;
using Mina.Filter.Ssl;
using Mina.Transport.Socket;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace TimerJobServer
{
    /// <summary>
    /// 用于通讯服务功能
    /// </summary>
    public class MinaServer
    {
        private readonly ILog logger = LogManager.GetLogger(typeof(MinaServer));

        /// <summary>
        /// 端口号
        /// </summary>
        private static int port = 1234;

        public static int Port
        {
            get { return MinaServer.port; }
            set { MinaServer.port = value; }
        }

        private IoAcceptor acceptor;
        /// <summary>
        /// 初始化监听功能
        /// </summary>
        public void InitSockListening()
        {
            try
            {
                acceptor = new AsyncSocketAcceptor();
                //acceptor.FilterChain.AddLast("logger", new LoggingFilter());
                acceptor.FilterChain.AddLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
                acceptor.Handler = handler;
                LogHelp.SetMinaLog(handler);//设置Sock返回日志信息
                acceptor.Bind(new IPEndPoint(IPAddress.Any, port));
                logger.Info("Listening on " + acceptor.LocalEndPoint);
            }
            catch (Exception ex)
            {
                logger.Fatal(port + ex.ToString());
            }
            
        }

        private MinaServerHandler handler  = new  MinaServerHandler();

        /// <summary>
        /// 停止监听功能
        /// </summary>
        public void StopListening()
        {
            //停止监听
            acceptor.Unbind();
        }
    }
}
